﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Users;
using Lists;
using Sim;

namespace Lists
{
    public class UserList : IUserList
    {
        static public List<User> userList { get; set; }

        public UserList()
        {
            userList = new List<User>();
        }

        int IUserList.AddUser(User u)
        {
            bool UniqueIDFound = false;
            int id = 0;
            DeserializeFromXML();
            for (int i = 0; i < userList.Count(); i++)
            {
                if (u.username == userList[i].username)
                {
                    return 0;
                }
            }
            while (UniqueIDFound == false)
            {
                id++;
                if (userList.Count() == 0)
                {
                    UniqueIDFound = true;
                    break;
                }
                for (int j = 0; j < userList.Count(); j++)
                {
                    if (id == userList[j].id)
                    {
                        UniqueIDFound = false;
                        break;
                    }
                    else if ((j == userList.Count() - 1) & (UniqueIDFound == false))
                    {
                        UniqueIDFound = true;
                        break;
                    }

                }
            }
            u.id = id;
            userList.Add(u);
            userList.Sort((x, y) => x.id.CompareTo(y.id));
            SerializeToXML();

            return 1;
        }

        void IUserList.RemoveUser(int index)
        {
            DeserializeFromXML();
            userList.RemoveAt(index);
            SerializeToXML();
        }

        static public void SerializeToXML()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<User>), new XmlRootAttribute("USERS"));
            TextWriter textWriter = new StreamWriter("users.xml");
            serializer.Serialize(textWriter, userList);
            textWriter.Close();
        }

        static public void DeserializeFromXML()
        {
            userList.Clear();
            XmlSerializer deserializer = new XmlSerializer(typeof(List<User>), new XmlRootAttribute("USERS"));
            TextReader textReader = new StreamReader("users.xml");
            userList = (List<User>)deserializer.Deserialize(textReader);
            textReader.Close();
        }

    }
}